package cn.itsource.org.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.itsource.basic.query.PageList;
import cn.itsource.basic.service.impl.BaseServiceImpl;
import cn.itsource.org.domain.Department;
import cn.itsource.org.mapper.DepartmentMapper;
import cn.itsource.org.query.DepartmentQuery;
import cn.itsource.org.service.IDepartmentService;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author CTL
 * @Description
 * @date Created in 2023-05-16 14:17
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department,DepartmentQuery> implements IDepartmentService {

    @Autowired
    private DepartmentMapper mapper;

    @Autowired
    private StringRedisTemplate   redisTemplate;

    //@Override
    //public List<Department> getAll() {
    //    return mapper.selectAll();
    //}

    //分页查询
    @Override
    public PageList<Department> getPageList(DepartmentQuery query) {
        //1.设置分页参数
        PageHelper.startPage(query.getPageNum(),query.getPageSize());
        //2.执行查询操作
        List<Department> list = mapper.getAllDepa(query);
        //3.封装分页数据
        PageInfo<Department> PageInfo = new PageInfo<>(list);
        //4.使用自己的工具类返回分页数据
        PageList<Department> PageList = new PageList<Department>(PageInfo.getTotal(),PageInfo.getList());
        //5.返回数据
        return PageList;
    }

    //添加，修改
    @Override
    public void addOrUpdate(Department department) {
        if(department.getId()==null){
            //没有id,添加
            mapper.insertSelective(department);
        }
        updeate(department);
        redisTemplate.delete("parentDept");
    }


    public void updeate(Department department){
        Long[] parentIds = department.getParentIds();
        if(parentIds!=null&&parentIds.length>0){
            StringBuffer sb = new StringBuffer();
            //将数组拆分成字符串
            for (Long parentId : parentIds) {
                sb.append("/"+parentId);
            }
            //拼接当前的部门ID
            sb.append("/"+department.getId());
            department.setDirPath(sb.toString());
            //取出ID，
            department.setParentId(parentIds[parentIds.length-1]);
            //修改
            mapper.updateByPrimaryKeySelective(department);
        }

    }

    //根据id删除
    //@Override
    //public void delete(Long id) {
    //
    //
    //    mapper.deleteByPrimaryKey(id);
    //    redisTemplate.delete("parentDept");
    //}

    //无限极树
    @Override
    public List<Department> treeDept() {
        //查询所有部门
        List<Department> departments = mapper.selectAll();
        //返回的结果集
        List<Department> treelist=new ArrayList<Department>();

        Map<Long,Department> map = new HashMap<Long,Department>();
        //给部门定义一个ID，方便查询
        for (Department dept : departments) {
            map.put(dept.getId(),dept);
        }

        for (Department dept : departments) {
            //如果没有父级部门
            if(dept.getParentId()==null){
                treelist.add(dept);
            }else {
                //有父级部门，就找到这个部门并给它下的children属性字段添加当前部门
                map.get(dept.getParentId()).getChildren().add(dept);
            }
        }

        return treelist;
    }

    //所有的父级部门

    @Override
    public List<Department> getAllParentDepa() {

        /*
        *   1. 每次查询，先看缓存是否有数据 ， 如果有：直接返回
            2. 如果缓存没有数据，去数据库查询数据
            3. 把数据同步一份到缓存
            4. 返回数据
        *
        * */
        // 定义一个返回的父级部门集合
        List<Department> depts = new ArrayList<>();
        // 1. 每次查询，先看缓存是否有数据 ， 如果有：直接返回
        String parentDept = redisTemplate.opsForValue().get("parentDept");
        // 2. 判断
        System.out.println(StrUtil.isEmpty(parentDept)+"-----------------------");
        if (StrUtil.isEmpty(parentDept)) {
            // 3. 如果缓存没有数据，去数据库查询数据
            // 4. 将查询到的数据放入redis中
            depts = mapper.getAllParentDepa();
            redisTemplate.opsForValue().set("parentDept", JSONObject.toJSONString(depts));

        } else {

            depts = (List<Department>) JSONObject.parse(parentDept);
        }
        return depts;
    }

    //是否是父级部门
    @Override
    public List<Department> whetherItIsAParentDepartment(Long id) {
        return mapper.whetherItIsAParentDepartment(id);
    }
}
